package org.changs.control.ui.home;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

import com.iot.push.sdk.ClientTypeEnum;
import com.iot.push.sdk.IoTCommunicationClient;
import com.iot.push.sdk.message.Audience;
import com.iot.push.sdk.message.Message;
import com.iot.push.sdk.message.MetaInfo;

import org.changs.aplug.base.BasePresenter;
import org.changs.aplug.utils.AppUtils;
import org.changs.aplug.utils.DeviceUtils;
import org.changs.aplug.utils.EmptyUtils;
import org.changs.aplug.utils.JsonUtils;
import org.changs.aplug.utils.NetworkUtils;
import org.changs.aplug.utils.WifiUtils;
import org.changs.control.event.RemoteIpEvent;
import org.changs.control.event.WifiApStateEvent;
import org.changs.control.push.ClientReceiver;
import org.changs.control.push.ConnectEvent;
import org.changs.control.push.LocationInfo;
import org.changs.control.push.PushContent;
import org.changs.control.push.PushMsg;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import aplug.AppManager;
import aplug.data.db.MachineHelper;
import aplug.data.db.model.Machine;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

/**
 * Created by yincs on 2017/9/6.
 */

public class HomePresenter extends BasePresenter<HomeContract.V> implements HomeContract.P {

    private final AppManager mAppManager;
    private final WifiManager mWifiManager;
    private final Context context;
    private final MachineHelper mMachineHelper;
    private final ConnectEvent connectEvent;
    private final ClientReceiver receiver;
    private final String appId;
    private final String appSecret;
    private final String clientId;
    private final List<String> tags;
    private final List<String> groups;
    private String alias;
    private LocationInfo location;

    @Inject
    public HomePresenter(Context context,
                         AppManager appManager,
                         MachineHelper machineHelper) {
        this.mAppManager = appManager;
        this.context = context;
        this.mMachineHelper = machineHelper;
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        connectEvent = new ConnectEvent();
        receiver = new ClientReceiver();
        appId = "9092c4ee91ee49d6870cc7c1900d907e";
        appSecret = "3eae59ff3d8142bdb8b4e2f06f1fcd19";
        clientId = DeviceUtils.getAndroidID(context);
        tags = new ArrayList<>();
        groups = new ArrayList<>();
    }

    @Override
    public void attachView(HomeContract.V v) {
        super.attachView(v);
        EventBus.getDefault().register(this);
        checkState();
        getMsgList();
    }

    @Override
    public void detachView() {
        super.detachView();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 是否有消息
     */
    public void getMsgList() {
        getCompositeDisposable().add(mAppManager.getPushMsgHelper().loadAll()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(pushMsgs -> {
                    if (pushMsgs.size() > 0) {
                        getMvpView().showMesg(true);
                    } else {
                        getMvpView().showMesg(false);
                    }
                }));
    }


    private void checkState() {
        String remoteIp = mAppManager.getRemoteIp();
        if (EmptyUtils.isEmpty(remoteIp)) {
            if (WifiUtils.isWifiApEnabled(mWifiManager)) {
                getMvpView().showConnecting();
            } else {
                getMvpView().showDisConnected();
            }
        } else {
            String msg = "设备名称：卡车安全助手\t序列号：C154654\n设备ip：" + remoteIp;
            getMvpView().showConnected(msg);
        }
    }

    @Override
    public void clickConnect() {
        mMachineHelper.loadAll()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(machines -> {
                    if (isDetachView()) return;
                    if (machines.size() == 0) {
                        getMvpView().startCaptureActivity();
                    } else {
                        openWifiApWaitConnect(machines.get(0));
                    }
                });
    }

    @Override
    public void clickDisConnect() {
        WifiUtils.closeWifiAp(mWifiManager);
    }

    @Override
    public void parseCaptureResult(String contents) {
        Machine machine;
        try {
            machine = JsonUtils.parseObject(contents, Machine.class);
        } catch (Exception e) {
            e.printStackTrace();
            getMvpView().onError("车机信息解析失败");
            return;
        }
        if (EmptyUtils.isEmpty(machine.getName())
                || EmptyUtils.isEmpty(machine.getSsid())
                || EmptyUtils.isEmpty(machine.getPwd())) {
            getMvpView().onError("车机信息不完整");
            return;
        }
        mMachineHelper.insertOrUpdate(machine)
                .subscribeOn(Schedulers.io())
                .subscribe();

        openWifiApWaitConnect(machine);
    }

    @Override
    public void finish() {
        WifiUtils.closeWifiAp(mWifiManager);
    }


    private void openWifiApWaitConnect(Machine machine) {
        final boolean openHotspot = WifiUtils.openHotspot(mWifiManager, machine.getSsid(), machine.getPwd());
        Timber.d("openHotspot = " + openHotspot);
        if (!openHotspot) Toast.makeText(context, "开启wifi热点失败", Toast.LENGTH_SHORT).show();
    }

    @Subscribe
    public void onEvent(RemoteIpEvent event) {
        if (WifiUtils.isWifiApEnabled(mWifiManager))
            checkState();
    }

    @Subscribe
    public void onEvent(WifiApStateEvent event) {
        if (event.state == 11 || event.state == 13)
            checkState();
    }


    /**
     * 消息推送
     *
     * @param locationInfo
     * @param clientId
     * @param appId
     * @return
     */
    public Message initMessage(LocationInfo locationInfo, String clientId, String appId) {
        Message message = new Message();
        message.setAudience(getAudience());
        message.setMetaInfo(getMetaInfo(locationInfo, clientId, appId));
        String msg = JsonUtils.stringify(message);
        Log.e("msg111 = ", msg);
        return message;
    }

    public MetaInfo getMetaInfo(LocationInfo locationInfo, String clientId, String appId) {
        MetaInfo metaInfo = new MetaInfo();
        metaInfo.setContentType("text/plain");
        metaInfo.setContent(getContent(locationInfo, clientId, appId));
        return metaInfo;
    }

    public Audience getAudience() {
        Audience audience = new Audience();
        audience.setTags("$SYS$");
        audience.setType(ClientTypeEnum.TAGS);
        return audience;
    }

    public String getContent(LocationInfo locationInfo, String clientId, String appId) {
        PushContent content = new PushContent();
        PushContent.BodyBean.LocationBean locationBean = content.getBody().getLocation().setProvinceName(locationInfo.getProvince())
                .setCityName(locationInfo.getCity()).setAreaName(locationInfo.getDistrict())
                .setAddress(locationInfo.getAddress())
                .setLon(locationInfo.getLongitude())
                .setLat(locationInfo.getLatitude());
        PushContent.BodyBean.AppVOBean appVOBean = content.getBody().getAppVO()
                .setAppName(AppUtils.getAppName(context))
                .setAppId(appId);
        content.setAction("DeviceUpload");


        content.getBody()
                .setLocation(locationBean)
                .setAppVO(appVOBean)
                .setOpType("ANDROID")
                .setClientId(clientId)
                .setDeviceModel(DeviceUtils.getModel())//设备型号
                .setManufacturers(DeviceUtils.getManufacturer())//设备厂商
                .setNetwork(NetworkUtils.getNetworkTypeName(context))
                .setAlias(alias)
                .setTags(tags)
                .setGroups(groups)
                .setOpVersion(DeviceUtils.getOpVersion());//操作系统版
        String body = JsonUtils.stringify(content.getBody());
        JSONObject json = new JSONObject();
        try {
            json.put("action", "DeviceUpload");
            json.put("body", body);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    public void initPush(final LocationInfo locationInfo) {
        location = locationInfo;
        Log.e("clientId=", clientId);
        try {
            IoTCommunicationClient.connect(appId, appSecret, clientId, receiver, connectEvent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //设置标签、别名
    public void setTagsAlias(final String tags, final String alias) {
        try {
            if (tags != null) {
                String[] cd = tags.split(",");
                for (int i = 0; i < cd.length; i++) {
                    this.tags.add(cd[i]);
                }

                IoTCommunicationClient.setTags(tags);
            }
            if (alias != null) {
                this.alias = alias;

                IoTCommunicationClient.setAlias(alias);
            }
            IoTCommunicationClient.sendTextMsg(initMessage(location, clientId, appId));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @Subscribe
//    public void onEvent(MessageEvent MessageEvent) {//初始化的回调
//        if (MessageEvent.getMsg().equals("连接成功。")) {//初始化成功开始设备上报
//            try {
//                IoTCommunicationClient.sendTextMsg(initMessage(location, clientId, appId));
//                setTagsAlias("APP,area,518000", null);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        } else if (MessageEvent.getMsg().equals("连接失败。")) {//初始化失败，再次初始化
//            try {
//                IoTCommunicationClient.connect(appId, appSecret, clientId, receiver, connectEvent);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 保存消息
     *
     * @param pushMsg
     */
    public void savaPush(PushMsg pushMsg) {
        getCompositeDisposable().add(mAppManager.getPushMsgHelper().insertOrUpdate(pushMsg)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe());
    }

}
